<?php

set_time_limit(0);
require_once 'db/Db.class.php';
require_once 'functions.php';
$db = new Db();
//get email template
$body = "";
$sql = "SELECT * FROM setting WHERE id = 3";
$template = $db->row($sql);
if ($template) {
    $body = $template['Value'];
}
//get email from
$sql = "SELECT * FROM setting WHERE id = 2";
$settingEmailFrom = $db->row($sql);
do{
    $time = 1;
    //time ping camera
    $sql = "SELECT * FROM setting WHERE id = 1";
    $settingTime = $db->row($sql);
    if(isset($settingEmailFrom['Value']) && isset($settingTime['Value'])){
        $from = $settingEmailFrom['Value'];
        $time = $settingTime['Value'];
        $sql = "SELECT cameras.*,customers.Email FROM cameras,customers WHERE cameras.CustId = customers.Id";
        $cameras = $db->query($sql);
        foreach ($cameras as $camera) {
            //ping camera
            $url = 'http://' . $camera["UniIp"] . ':' . $camera["HttpPort"] . '/cgi-bin/encoder?USER=' . $camera["UserName"] . '&PWD=' . $camera["Password"] . '&GET_STREAM';
            $ping = pingCammera($url);
            //update camera
            $sql = "UPDATE cameras SET ";
            $dataUpdate = array();
            $dataUpdate['UptDt'] = date('Y-m-d h:i:s');
            $dataUpdate['Off'] = $ping ? 0 : 1;
            if (strtotime(date('y-m-d', strtotime($camera["UptDt"]))) == strtotime(date('Y-m-d'))) {
                if ($camera['SendMail'] == 0) {
                    if (!$ping) {
                        sendMail($camera['Email'], array('camera_id' => $camera['CamID']),$body,$from);
                        $dataUpdate['SendMail'] = 1;
                    }
                }
            } else {
                if (!$ping) {
                    sendMail($camera['Email'], array('camera_id' => $camera['CamID']),$body, $from);
                    $dataUpdate['SendMail'] = 1;
                } else {
                    $dataUpdate['SendMail'] = 0;
                }
            }
            foreach ($dataUpdate as $key => $value) {
                $sql .= " `" . $key . "` = :" . $key . ",";
            }
            $sql = trim($sql, ',');
            $sql .= " WHERE Id = " . $camera['Id'];
            $db->query($sql, $dataUpdate);
        }
    }
    sleep($time);
}while($time > 1);


